package com.tac.service.impl;

import com.alibaba.fastjson.JSON;
import com.tac.common.Exception.CostomException;
import com.tac.common.result.Result;
import com.tac.common.thread.Thread;
import com.tac.common.util.ImgUtis;
import com.tac.dao.UserDao;
import com.tac.pojo.User;
import com.tac.pojo.vo.Page;
import com.tac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class UserServiceImpl implements UserService {
    @Value("${shopping.path}")
    private String BasePath;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${shopping.path}")
    private  String baserl;
    @Override
    public Result<User> login(User user) {
        User userAndName = userDao.selectByphone(user);
        if(userAndName==null){
            return Result.error("此手机号尚未注册");
        }
        String password = user.getPassword();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5DigestAsHex);
        User loginUser = userDao.login(user);
        if(loginUser!=null){
            String key = UUID.randomUUID().toString();
            String jsonString = JSON.toJSONString(loginUser);
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key,jsonString);//先不设置失效时间

            return Result.success(loginUser,key);
        }else {
            return Result.error("密码错误");
        }

    }

    @Override
    public Result logout(String token) {
        Boolean delete = redisTemplate.delete(token);
        if(delete){
            return Result.success(null,"success");
        }else{
            return Result.error("退出失败");
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public Result<User> rigister(User user,Integer code) {
        User user1 = userDao.selectByphone(user);
        if(user1!=null){
            return Result.error("手机号已注册请登录，如忘记密码请找回");
        }
        Boolean aBoolean = redisTemplate.hasKey(code+"");
        if(!aBoolean){
            return Result.error("验证码错误或过期");
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String user2 = (String) valueOperations.get(code+"");
        User user3 = JSON.parseObject(user2, User.class);
        if(!user3.getPhone().equals(user.getPhone())){
            return Result.error("验证码错误");
        }
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setType("user");
        user.setBalance(new BigDecimal(0));
        Integer insert = userDao.insert(user);
        if(insert>0){
            return Result.success(null,"恭喜你注册成功");
        }
        throw new CostomException("服务器异常请联系管理员");
    }

    /**
     * 发送验证码
     * @param user
     * @return
     */
    public Result<Integer> code(User user){
        int code = new Random().nextInt(9999);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String s = JSON.toJSONString(user);
        valueOperations.set(code+"",s,60,TimeUnit.SECONDS);
        return Result.success(code,"success");
    }

    /**
     * 充值         还要加入充值表还没写
     * @return
     */
    public Result Recharge(BigDecimal money){
        Integer id = Thread.getId();
        User user = userDao.selecyById(id);
        BigDecimal qian=user.getBalance();
        user.setBalance(qian.add(money));
        userDao.updateByid(user);
       return Result.success(null,"充值成功");
    }

    /**
     * 上传头像
     * @param file
     * @return
     */
    @Override
    public Result updateByImg(MultipartFile file)  {
        String imgName = null;

        imgName = ImgUtis.saveimg(file,baserl);
        Integer id = Thread.getId();
        userDao.updateByImg(imgName,id);
        return Result.success(null,imgName);
    }

    /**
     * 根据id修改密码
     * @param
     * @return
     */
    public Result updatePwdByid(String password){
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        userDao.updatePwdByid(Thread.getId(),s);
      return Result.success(null,"success");
    }
//---------------------------------------------------------------------

    /**
     * 查看所有用户
     * @return
     */
    @Override
    public Result<Page<List<User>> > selectAll(int page,int limit) {
        Integer TotalLimit = userDao.selectAllByCount();
        List<User> users = userDao.selectAll((page-1)*limit,limit);
        Page<List<User>> listPage = Page.get(users, TotalLimit, limit);

        return Result.success(listPage,"success");
    }

    /**
     * 管理员添加用户
     * @param user
     * @return
     */
    public Result createrUser(User user){
        User user1 = userDao.selectByphone(user);
        if(user1!=null){
            return Result.error("手机号已注册请登录，如忘记密码请找回");
        }
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setType("user");
        Integer insert = userDao.insert(user);
        if(insert>0){
            return Result.success(null,"恭喜你注册成功");
        }
        throw new CostomException("服务器异常请联系管理员");
    }

    /**
     * 修改用户信息 可以修改余额
     * @param user
     * @return
     */
    public Result updateByid(User user){
        userDao.updateByid(user);
        return Result.success(null,"success");
    }

    /**
     * 修改用户状态 停用启用删除
     * @param
     * @return
     */
    public Result updateByid(Integer id,Integer status){
        User user = userDao.selecyById(id);
        user.setStatus(status);
        userDao.updateByid(user);
        return Result.success(null,"success");
    }

}
